<?php

namespace app\model\oa;

use think\Model;
use think\model\concern\SoftDelete;

/**
 * 审批流程模型
 * @package app\model\oa
 */
class Approve extends Model
{
    use SoftDelete;

    // 表名
    protected $name = 'approve';

    // 主键
    protected $pk = 'id';

    // 自动时间戳
    protected $autoWriteTimestamp = true;
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = 'delete_time';

    // 字段类型转换
    protected $type = [
        'id' => 'integer',
        'user_id' => 'integer',
        'type' => 'integer',
        'title' => 'string',
        'content' => 'string',
        'status' => 'integer',
        'current_step' => 'integer',
        'attachment' => 'json',
        'create_time' => 'int',
        'update_time' => 'int',
        'delete_time' => 'int',
    ];

    // 审批类型常量
    const TYPE_LEAVE = 1;        // 请假审批
    const TYPE_EXPENSE = 2;      // 费用审批
    const TYPE_PURCHASE = 3;     // 采购审批
    const TYPE_CONTRACT = 4;     // 合同审批
    const TYPE_PROJECT = 5;      // 项目审批
    const TYPE_OTHER = 99;       // 其他审批

    // 审批状态常量
    const STATUS_PENDING = 0;      // 待审批
    const STATUS_APPROVED = 1;   // 已批准
    const STATUS_REJECTED = 2;   // 已拒绝
    const STATUS_CANCELLED = 3;  // 已取消
    const STATUS_PROCESSING = 4;   // 审批中

    /**
     * 获取类型文本
     */
    public static function getTypeText($type)
    {
        $texts = [
            self::TYPE_LEAVE => '请假审批',
            self::TYPE_EXPENSE => '费用审批',
            self::TYPE_PURCHASE => '采购审批',
            self::TYPE_CONTRACT => '合同审批',
            self::TYPE_PROJECT => '项目审批',
            self::TYPE_OTHER => '其他审批',
        ];
        return $texts[$type] ?? '未知';
    }

    /**
     * 获取状态文本
     */
    public static function getStatusText($status)
    {
        $texts = [
            self::STATUS_PENDING => '待审批',
            self::STATUS_APPROVED => '已批准',
            self::STATUS_REJECTED => '已拒绝',
            self::STATUS_CANCELLED => '已取消',
            self::STATUS_PROCESSING => '审批中',
        ];
        return $texts[$status] ?? '未知';
    }

    /**
     * 关联用户
     */
    public function user()
    {
        return $this->belongsTo('app\model\admin\User', 'user_id', 'id');
    }

    /**
     * 关联审批记录
     */
    public function records()
    {
        return $this->hasMany(\app\model\workflow\WorkflowApproval::class, 'business_id', 'id')
            ->where('business_type', 'approve');
    }

    /**
     * 获取审批列表
     */
    public static function getList($params = [])
    {
        $query = self::with(['user'])->order('create_time', 'desc');

        // 按类型筛选
        if (!empty($params['type'])) {
            $query->where('type', $params['type']);
        }

        // 按状态筛选
        if (isset($params['status']) && $params['status'] !== '') {
            $query->where('status', $params['status']);
        }

        // 按用户筛选
        if (!empty($params['user_id'])) {
            $query->where('user_id', $params['user_id']);
        }

        // 按标题搜索
        if (!empty($params['title'])) {
            $query->where('title', 'like', '%' . $params['title'] . '%');
        }

        // 时间范围
        if (!empty($params['start_time'])) {
            $query->where('create_time', '>=', $params['start_time']);
        }
        if (!empty($params['end_time'])) {
            $query->where('create_time', '<=', $params['end_time']);
        }

        return $query->paginate($params['limit'] ?? 15);
    }

    /**
     * 获取我的审批
     */
    public static function getMyApproves($userId, $status = null)
    {
        $query = self::where('user_id', $userId)->order('create_time', 'desc');

        if ($status !== null) {
            $query->where('status', $status);
        }

        return $query->select();
    }

    /**
     * 获取待我审批的
     */
    public static function getPendingApproves($userId)
    {
        return self::where('status', self::STATUS_PENDING)
            ->order('create_time', 'desc')
            ->select();
    }

    /**
     * 创建审批
     */
    public static function createApprove($data)
    {
        try {
            $approve = new self();
            $approve->user_id = $data['user_id'];
            $approve->type = $data['type'];
            $approve->title = $data['title'];
            $approve->content = $data['content'] ?? '';
            $approve->status = self::STATUS_PENDING;
            $approve->current_step = 1;
            $approve->attachment = $data['attachment'] ?? [];
            $approve->save();

            return $approve;
        } catch (\Exception $e) {
            throw new \Exception('创建审批失败：' . $e->getMessage());
        }
    }

    /**
     * 更新审批状态
     */
    public function updateStatus($status, $remark = '')
    {
        $this->status = $status;
        if ($status == self::STATUS_APPROVED) {
            $this->current_step = 999; // 标记为已完成
        }
        $this->save();

        // 记录审批历史
        $this->addApprovalRecord($status, $remark);
    }

    /**
     * 添加审批记录
     */
    protected function addApprovalRecord($status, $remark)
    {
        // 这里需要调用WorkflowApproval模型记录审批历史
        // 具体实现取决于工作流系统
    }

    /**
     * 搜索器 - 类型
     */
    public function searchTypeAttr($query, $value)
    {
        $query->where('type', $value);
    }

    /**
     * 搜索器 - 状态
     */
    public function searchStatusAttr($query, $value)
    {
        $query->where('status', $value);
    }

    /**
     * 搜索器 - 用户ID
     */
    public function searchUserIdAttr($query, $value)
    {
        $query->where('user_id', $value);
    }

    /**
     * 搜索器 - 标题
     */
    public function searchTitleAttr($query, $value)
    {
        $query->where('title', 'like', '%' . $value . '%');
    }

    /**
     * 搜索器 - 创建时间范围
     */
    public function searchCreateTimeAttr($query, $value)
    {
        if (is_array($value) && count($value) == 2) {
            $query->whereBetween('create_time', $value);
        }
    }
}